package com.sunny.fetch.common;

import com.sunny.fetch.mapper.SunSystemMapper;
import com.sunny.fetch.pojo.SunSystem;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Component
@Data
@Slf4j
public class SysConfig implements ApplicationListener<ContextRefreshedEvent> {

    private static SysConfig sysConfig;
    private String accessToken;
    private String baseUrl;

    @Autowired
    private SunSystemMapper systemMapper;

    private void initConfig() {
        log.info("系统已经启动，开始加载系统配置");
        Example example = new Example(SunSystem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("keyType", "tushare");
        List<SunSystem> items = systemMapper.selectByExample(example);
        items.forEach(i->{
            if ("access_token".equals(i.getSysKey())) {
                accessToken = i.getSysValue();
            } else if ("base_url".equals(i.getSysKey())) {
                baseUrl = i.getSysValue();
            }
        });
        log.info("加载系统配置完毕");
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        initConfig();
        sysConfig = this;
    }

    public static SysConfig get() {
        return sysConfig;
    }
}
